var grid = null;//表格对象
var treeManger; //树对象
var data;
var userManger;
var mallList=$("#mallList");
var $modal = $('#ajax-modal');
var $smallModal = $("#smallModal");
var btnAddNew = $("#btnAddNew");
var btnUpdate = $("#btnUpdate");
var btnStart = $("#btnStart");
var btnStop = $("#btnStop");
var btnRePwd = $("#btnRePwd");
var btnDel = $("#btnDel");
var roleid = document.getElementById("roleid").value;
//if (roleid == "0") {
//	document.getElementById("btnAddNew").style.visibility = "hidden";// 隐藏
//}
/*
 * 初始化加载
 */
$(function () {
    btnAddNew.click(function (e) {
        addNew();
    });
    btnUpdate.click(function (e) {
        updUserInit();
    });
    btnStart.click(function (e) {
        updUserStatus("01");
    });
    btnStop.click(function (e) {
        updUserStatus("02");
    });
    btnRePwd.click(function (e) {
        resetPassword();
    });
    btnDel.click(function (e) {
        delUser();
    });

    $modal.on('hidden.bs.modal', function (e) {
        removeDetail();
    })
    //查询用户信息列表
    var	liveid = $("#liveid").val();
    var totals = document.getElementById("totals").value;
    var url = _path + "/label/list";
    findUserInfoList(url);
    $("#Submitbutton").bind("click", function () {
        var name = $("#name").val();

        var url = "/label/list?name=" + name;
        findUserInfoList(url);
    });
});
//查询
function getmallList(){

	   var url = _path + "/label/list";
	   findUserInfoList(url);
}


function getWhere(attrs) {
    if (!grid || !attrs) return null;
    var clause = function (rowdata, rowindex) {
        for (var i = 0, len = attrs.length; i < len; i++) {
            if ((rowdata[attrs[i]].toLowerCase().indexOf($("#" + attrs[i]).val().toLowerCase()) == -1)) {
                return false;
            }
        }
        return true;
    };
    return clause;
}

/*
 * 查询用户信息列表数据
 */
function findUserInfoList(url) {
	var name = $("#name1").val();
	var liveid = $("#liveid").val();
	 $.ajax({
	        url: url,
	        type: "POST",
	        data: {name:""+name+"",liveid:""+liveid+""},
	        async: false,
	        dataType: "json",
	        success: function (result) {
	            data = result;
	            var pageSize = 20;
	            grid = $("#maingrid").ligerGrid({
	                width: '98%',
	                height: '98%',
	                headerRowHeight: 36,
	                rowHeight: 36,
	                checkbox: true,
	                columns: [
	                    { display: 'ID', name: 'id', width: '20%', align: 'left', hide: true},
	                    { display: '页签名', name: 'name', width: '20%' },
	                    { display: '顺序', name: 'sort', width: '5%' },
	                    { display: '所属直播', name: 'live.name', width: '35%' },
	                    { display: '操作员', name: 'user.username', width: '20%' }
	                ], where: getWhere(), data: data, pageSize: 20, pageParmName: "curNo", pagesizeParmName: "curSize"
	            });
	            $("#pageloading").hide();
	        }
	    });
	
	
}



function save() {
    if(validation()){ // 校验提交
    App.ajax(_path + "/label/addlabel", $("#formDetail").serialize(), saveResult);
	}
}

/**
 * 校验input
 * @return
 */
function validation() {
    var value0 = $("#formDetail #name").val();
    if (value0.replace(/(^\s*)|(\s*$)/, "").length == 0) {
        App.bubble(500, "页签不能为空！");
        return false;
    }  

    var sort = $("#formDetail #sort").val();
    if (sort.replace(/(^\s*)|(\s*$)/, "").length == 0) {
        App.bubble(500, "顺序不能为空！");
        return false;
    }
    return true;
}


function saveResult(data) {

	var data=data.statusCode;
    if (data == '200') {
        App.bubble(200, "保存成功！");
        $modal.modal('hide');
        findUserInfoList(_path + "/user/list");
        window.location.reload();
    } else if (data == '500') {
        App.bubble(500, "保存失败！");
    } else if (data == '409') {
        App.bubble(500, "该用户已存在！");
    }
}

/*
 * 新增用户信息初始化
 */
function addNew() {
	  initOgrTree();
    $modal.modal('show');
}

/*
 * 修改用户信息初始化
 */
function updUserInit() {
    //获取选中记录行
    var rowid = grid.getSelecteds();
    var length = rowid.length;
    if (length == 0) {
        App.bubble(500, "请选择需要修改的！");
        return false;
    }
    if (length == 1) {
        App.ajax(_path + "/label/updlabelInit", "id=" + rowid[0].id, function (data) {
        	initOgrTree();
        	$("#labelid").val(data.labelid);
        	$("#id").val(data.id);
            $("#name").val(data.name);
            $("#sort").val(data.sort);
          
        });
        $modal.modal('show');
    } else {
        App.bubble(500, "只能选择一个用户信息进行修改！");
    }
}

function removeDetail(data) {
    $(':input', '#formDetail')
        .not(':button, :submit, :reset')
        .val('').removeAttr('checked').removeAttr('selected');
}

/*
 *删除选中的用户信息 
 */
function delUser() {
  
    var userId = '';
    //获取选中记录行
    var rowid = grid.getSelecteds();
    var length = rowid.length;
    if (length == 0) {
        App.bubble(500, "请选择要删除的记录！");
        return false;
    } else if (length > 0) {
   
       if (confirm('确实要删除选择的' + rowid.length + '条记录吗')) {
            for (var i = 0; i < length; i++) {//获取删除的ID
                if (i < length - 1) {
                    userId += rowid[i].id + ",";
                } else {
                    userId += rowid[i].id;
                }
            }
            $.ajax({
                type: "post",
                url: _path + "/label/dellabel",
                data: {
                    "userIds": userId
                },
                success: function (data) {
                    //如果删除成功，则刷新页面！
                    if (data["message"] == "1") {
                        App.bubble(200, "删除成功！");
                    } else if (data["message"] == "0") {
                        App.bubble(500, "删除失败！");
                    } else {
                        App.bubble(500, data["message"]);
                    }
                    //删除用户信息后查询初始化
                    findUserInfoList(_path + "/label/list");
                },
                error: function () {
                    App.bubble(500, "删除失败！");
                }
            });

        }
    }
}


//------详细信息修改-----
/**
 * @title : 以树的形式展示机构
 * */
function initOgrTree() {
    var url = _path + "/label/organTree";
    $.ajax({
        type: "post",
        url: url,
        async: false,
        success: function (data) {
            var treeData = [];
//            treeData.push({
//                'id': '999999',
//                'icon': '',
//                'text': '机构列表',
//                'isexpand': true,
//                'pid': ""
//            });
            var orgList = data.orgList;
            for (var i = 0; i < orgList.length; i++) {
                treeData.push({
                    'id': orgList[i].id,
                    'icon': '',
                    'text': orgList[i].value0,
                    'isexpand': true,
                });
            }
            loadTree(treeData);
        }
    });
}

//------详细信息修改-----

//加载树
function loadTree(dataTree) {
    var $$ = $("#orgTree");
    $$.html("<div style='height: 350px;overflow-y: auto'></div>");
    treeManger = $$.children().ligerTree({
        data: dataTree,
        idFieldName: 'id',
        parentIDFieldName: 'pid',
        checkbox: false,
        slide: true,
        nodeWidth: 120,
        onSelect: onSelect
    });
    var nodeId = $("#labelid").val();
    if (nodeId != '-1' && nodeId != '') {
        var data = treeManger.getDataByID(nodeId);
        onclickPass(data);
        treeManger.selectNode(nodeId);
    }
}


function onSelect(note) {
    onclickPass(note.data);
}
function onclickPass(data) {
    var orgId = data.id;
    var value0 = data.text;
        $("#labelid").val(orgId);
        $("#name0").val(value0);
        $("#name").val(value0);
}
